package com.quxue.im.controller;

import cn.hutool.core.util.RandomUtil;
import com.quxue.im.req.user.SendCodeReq;
import com.quxue.im.req.user.LoginByCodeReq;
import com.quxue.im.req.user.LoginReq;
import com.quxue.im.req.user.RegisterReq;
import com.quxue.im.req.user.ForgetReq;
import com.quxue.im.util.SmsUtils;
import com.quxue.im.vo.AjaxResult;
import com.quxue.im.entity.ChatUser;
import com.quxue.im.service.IChatUserService;
import com.quxue.im.util.RedisUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

import static com.quxue.im.common.enums.SmsTypeEnum.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author jinken
 * @since 2023-11-10
 */
@RestController
@RequestMapping("/auth")
public class ChatUserController {


    @Resource
    private RedisUtils redisUtils;

    @Resource
    private IChatUserService chatUserService;

    @Resource
    private SmsUtils smsUtils;

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping("/login")
    public AjaxResult login(@RequestBody LoginReq loginReq) {
        AjaxResult result = chatUserService.login(loginReq);
        return result;
    }


    @RequestMapping("/register")
    public AjaxResult register(@RequestBody RegisterReq registerReq) {
        AjaxResult result = chatUserService.register(registerReq);
        return result;
    }


    @RequestMapping("/sendCode")
    public AjaxResult sendCode(@RequestBody SendCodeReq sendCodeReq) {
        ChatUser chatUser = chatUserService.selectByPhone(sendCodeReq.getPhone());

        String random = RandomUtil.randomNumbers(4);

        if (REGISTER.getType() == sendCodeReq.getType()) {
            if (Objects.nonNull(chatUser)) {
                return AjaxResult.error("账号已经注册直接登录");
            }
        } else if (LOGIN.getType() == sendCodeReq.getType()) {
            if (Objects.isNull(chatUser)) {
                return AjaxResult.error("账号不存在，请注册");
            }
        } else if (FORGET.getType() == sendCodeReq.getType()) {
            if (Objects.isNull(chatUser)) {
                return AjaxResult.error("您找回的账号不存在");
            }
        }
        //发送数据到redis，5分钟有效
        smsUtils.sendSms(sendCodeReq.getPhone(), random,sendCodeReq.getType());
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", random);
        return AjaxResult.success(map);
    }

    @RequestMapping("/forget")
    public AjaxResult forget(@RequestBody ForgetReq forgetReq) {
        return chatUserService.forget(forgetReq);
    }

    @RequestMapping("/loginByCode")
    public AjaxResult loginByCode(@RequestBody LoginByCodeReq loginReq) {
        AjaxResult result = chatUserService.loginByCode(loginReq);
        return result;
    }
}
